/**
 * 
 */
package PMCHandler;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;

import DBHandler.PostgreSQLJDBC;
import util.FileUtil;

/**
 * Get record in PMC full-text XML format with an identifier.
 * using PMC-OAI interface.
 *
 */
public class GetPMCRecord {
	
	public static String pubmed2PMCID(String pubMedID) throws IOException, JSONException
	{
		String pmcID=null;
		String converterBaseURL=" http://www.pubmedcentral.nih.gov/utils/idconv/v1.0/?ids=";
		if(pubMedID!=null && !pubMedID.equals(""))
		{
			converterBaseURL=converterBaseURL+pubMedID+"&format=json";
			JSONObject jsonObjID=readJsonFromUrl(converterBaseURL);
			try{
			String status = jsonObjID.getString("status");			
			if(status.equalsIgnoreCase("ok"))
			{
				JSONArray recordsArr = (JSONArray) jsonObjID.get("records");
				for(int n = 0; n < recordsArr.length(); n++)
				{
					JSONObject object = recordsArr.getJSONObject(n);
					
					if(object.has("pmcid"))
						return object.getString("pmcid");						
					else
					{
						String errmsg = object.getString("errmsg");
						System.out.println("No PMC id exist for mutation :"+errmsg);
						return "";
					}
				}
//				JSONObject first = (JSONObject)results.get(0);
//				pmcID=first.getString("pmcid");
			}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		return pmcID;
		
	}
	
	public static boolean downloadFullXML(String rawpmcID,String fileName,String proteinName,String id)
	{
		boolean downloadSuccess=false;
		String filesFolder = "files/";
		String xmlPUBMEDBaseURL="http://www.pubmedcentral.nih.gov/oai/oai.cgi?verb=GetRecord&identifier=oai:pubmedcentral.nih.gov:";
		String xmlBIOMEDBaseURL="";
		if(rawpmcID!=null && !rawpmcID.equals(""))
		{
			try{
				String pmcID=rawpmcID.substring(3, rawpmcID.length());
				URL pubmedURL = new URL(xmlPUBMEDBaseURL+pmcID+"&metadataPrefix=pmc");	
				URL biomedURL=new URL(xmlBIOMEDBaseURL);
				URLConnection conn = pubmedURL.openConnection();
		
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document doc = builder.parse(conn.getInputStream());
				TransformerFactory xmlfactory = TransformerFactory.newInstance();
				Transformer xform = xmlfactory.newTransformer();
				StreamResult result = new StreamResult(new StringWriter());
				xform.transform(new DOMSource(doc), result);
				String xmlContent=result.getWriter().toString();
				//boolean success = (new File(filesFolder+fileName+"/"+proteinName)).mkdir();
				//No Need to save in folders as below code will save it in the database
				/*if(!FileUtil.pathExists(filesFolder+fileName+"/"+proteinName+"/")) {
					FileUtil.createDirectory(filesFolder+fileName+"/"+proteinName+"/");					
				}
				File file=new File(filesFolder+fileName+"/"+proteinName+"/"+id+".xml");
				String encode="UTF-8";
				FileUtils.writeStringToFile(file, xmlContent,encode);*/
				PostgreSQLJDBC.saveXMLtoDB(rawpmcID, xmlContent);
				downloadSuccess=true;
			}
			catch (Exception e) {
				downloadSuccess= false;
				e.printStackTrace();
				PostgreSQLJDBC.saveXMLtoDB(rawpmcID, "");
			}
		}
		return downloadSuccess;
		
	}
	public static JSONObject readJsonFromUrl(String url) {
		    InputStream is;
			try {
				is = new URL(url).openStream();
				Reader readr=new InputStreamReader(is, Charset.forName("UTF-8")); 
		        BufferedReader rd = new BufferedReader(readr);
		        String jsonText = readAll(rd);
		        JSONObject json = new JSONObject(jsonText);
		        is.close();
		        return json;
			} catch (IOException | JSONException e) {
				System.err.println( e.getClass().getName()+": "+ e.getMessage() );
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}			
	  }
		
	private static String readAll(Reader rd) throws IOException {
			    StringBuilder sb = new StringBuilder();
			    int cp;
			    while ((cp = rd.read()) != -1) {
			      sb.append((char) cp);
			    }
			    return sb.toString();
	  }
}
